package com.lml.hydrogenexpertsystem.backend.service;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import okhttp3.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class AIService {
    @Value("${ai.deepseek.url}")
    private String apiUrl;

    @Value("${ai.deepseek.api-key}")
    private String apiKey;

    // 复用Client实例
    private final OkHttpClient client;
    private final ObjectMapper objectMapper;

    public AIService() {
        this.client = new OkHttpClient.Builder()
                .connectTimeout(30, TimeUnit.SECONDS)
                .readTimeout(60, TimeUnit.SECONDS)
                .build();
        this.objectMapper = new ObjectMapper();
    }

    public String generateAnswer(String question, List<String> context) {
        try {
            // 1. 构建消息结构
            List<Map<String, String>> messages = new ArrayList<>();

            messages.add(Map.of(
                    "role", "system",
                    "content", "你是一个新能源制氢领域的专业助手，请根据提供的背景知识回答问题，答案需包含数据支撑，拒绝编造信息"
            ));

            messages.add(Map.of(
                    "role", "user",
                    "content", buildPrompt(question, context)
            ));

            // 2. 构建规范化的请求体
            Map<String, Object> requestBody = new HashMap<>();
            requestBody.put("model", "deepseek-chat");
            requestBody.put("temperature", 0.7);
            requestBody.put("messages", messages); // 关键修复点

            // 3. 生成安全JSON
            String requestJson = objectMapper
                    .writerWithDefaultPrettyPrinter()
                    .writeValueAsString(requestBody);
            System.out.println("===> 发送的请求体：\n" + requestJson);

            // 3. 使用Jackson序列化
            RequestBody body = RequestBody.create(
                    requestJson,
                    MediaType.parse("application/json")
            );

            // 4. 构建请求
            Request request = new Request.Builder()
                    .url(apiUrl)
                    .post(body)
                    .addHeader("Authorization", "Bearer " + apiKey)
                    .build();

            // 5. 发送请求并处理响应
            try (Response response = client.newCall(request).execute()) {
                System.out.println("===> 响应状态: " + response.code());

                if (!response.isSuccessful() || response.body() == null) {
                    System.err.println("请求失败: " + response.code());
                    return "服务暂时不可用";
                }

                // 6. 解析响应
                String responseBody = response.body().string();
                System.out.println("===> 原始响应: " + responseBody); // 调试日志
                return extractAnswerFromJson(responseBody);
            }

        } catch (IOException e) {
            System.err.println("API请求异常: " + e.getMessage());
            return "连接AI服务失败";
        } catch (Exception e) {
            System.err.println("系统异常: " + e.getMessage());
            return "系统处理错误";
        }
    }

    private String buildPrompt(String question, List<String> context) {
        return String.format("请根据以下知识回答问题：\n%s\n问题：%s",
                String.join("\n", context), question);
    }

    private String extractAnswerFromJson(String json) {
        try {
            JsonNode root = objectMapper.readTree(json);
            if (root.has("error")) {
                return "API错误: " + root.get("error").get("message").asText();
            }
            return root.at("/choices/0/message/content").asText("未找到有效回答");
        } catch (Exception e) {
            return "解析响应失败";
        }
    }
}